﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Sinacor.Infra.Core.Licensing;
using Sinacor.Infra.Core.Licensing.Business;
using System.Collections.Generic;

namespace WebLicenseGenerator
{
	public partial class SearchLicenses : System.Web.UI.Page
	{
		Licensing licenseSearch;
		Licenca licenseBusiness;
        
		Sinacor.Infra.Core.Licensing.Business.Alias _aliasBusiness = null;
        
        int _selectedAliasCode
        {
            get
            {
                if (ViewState["SelectedAliasCode"] != null)
                    return Convert.ToInt32(ViewState["SelectedAliasCode"]);
                else
                    return 0;
            }
            set { ViewState["SelectedAliasCode"] = value; }
        }
        List<Sinacor.Infra.Core.Licensing.Alias> _aliasTable
        {
            get { return ViewState["AliasTable"] as List<Sinacor.Infra.Core.Licensing.Alias>; }
            set { ViewState["AliasTable"] = value; }
        }

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				cbLicenseType.Items.Add("");
				cbLicenseType.Items.Add(new ListItem(Sinacor.Infra.Core.Licensing.Treaty.Completa.ToString(), ((int)Sinacor.Infra.Core.Licensing.Treaty.Completa).ToString()));
				cbLicenseType.Items.Add(new ListItem(Sinacor.Infra.Core.Licensing.Treaty.Modulo.ToString(), ((int)Sinacor.Infra.Core.Licensing.Treaty.Modulo).ToString()));
				cbLicenseType.Items.Add(new ListItem(Sinacor.Infra.Core.Licensing.Treaty.Trial.ToString(), ((int)Sinacor.Infra.Core.Licensing.Treaty.Trial).ToString()));
				cbLicenseType.Items.Add(new ListItem(Sinacor.Infra.Core.Licensing.Treaty.Usuario.ToString(), ((int)Sinacor.Infra.Core.Licensing.Treaty.Usuario).ToString()));
				cbLicenseType.SelectedIndex = -1;

                gvLicenses.RowCommand += new GridViewCommandEventHandler(gvLicenses_RowCommand1);

				this.LoadAliases();
			}
		}

		protected void btSearch_Click(object sender, EventArgs e)
		{
			if (ValidatePageFields())
			{
				List<Licensing> licenses;
				licenseSearch = new Sinacor.Infra.Core.Licensing.Licensing();
				licenseBusiness = new Licenca();

				if (cbAliases.SelectedIndex > 0)
				    licenseSearch.AliasId = Convert.ToInt32(cbAliases.SelectedItem.Value);
				else
				    licenseSearch.AliasId = null;

				if (String.IsNullOrEmpty(txtLicenseId.Text.Trim()))
					licenseSearch.Id = null;
				else
					licenseSearch.Id = Convert.ToInt32(txtLicenseId.Text.Trim());

				if (String.IsNullOrEmpty(dpStartDate.Text))
					licenseSearch.Created = null;
				else
					licenseSearch.Created = new DateTime(Int32.Parse(dpStartDate.Text.Substring(6, 4)), Int32.Parse(dpStartDate.Text.Substring(3, 2)), Int32.Parse(dpStartDate.Text.Substring(0, 2)));

				if (cbLicenseType.SelectedIndex <= 0)
					licenseSearch.Treaty = null;
				else
				{
					switch (cbLicenseType.SelectedValue)
					{
						case "1":
							licenseSearch.Treaty = Treaty.Trial;
							break;
						case "2":
							licenseSearch.Treaty = Treaty.Modulo;
							break;
						case "3":
							licenseSearch.Treaty = Treaty.Usuario;
							break;
						case "4":
							licenseSearch.Treaty = Treaty.Completa;
							break;
					}
				}

				licenses = licenseBusiness.Selecionar(licenseSearch);

                if (licenses.Count != 0)
                {
                    if (licenses[0].Companies[0].CompanyId != null)
                        Session["CodCorr"] = Convert.ToString(licenses[0].Companies[0].CompanyId);

                    if (licenses[0].Id != null)
                        Session["CodLic"] = Convert.ToString(licenses[0].Id);

                    if (licenses[0].AliasId != null)
                        Session["CodAlia"] = Convert.ToString(licenses[0].AliasId);

                    if (licenses[0].Treaty != null)
                        Session["TipoLic"] = Convert.ToString(licenses[0].Treaty);
                }
                

				if (licenses.Count == 0)
					this.ShowMessageDialog("Nenhum dado encontrado", "Não foram encontrados dados que satisfaçam a pesquisa.");

				gvLicenses.DataSource = licenses;
				gvLicenses.DataBind();
			}
		}

		void LoadAliases()
		{
			_aliasBusiness = new Sinacor.Infra.Core.Licensing.Business.Alias();
            _aliasTable = _aliasBusiness.Selecionar(new Sinacor.Infra.Core.Licensing.Alias());

			cbAliases.DataSource = _aliasBusiness.Selecionar(new Sinacor.Infra.Core.Licensing.Alias());
			cbAliases.DataTextField = "Nome";
			cbAliases.DataValueField = "ID";
			cbAliases.DataBind();
			cbAliases.Items.Insert(0, "");
		}

		void ShowMessageDialog(string title, string message)
		{
			WebLicenseGenerator.UC.Messaging messaging = ((WebLicenseGenerator.UC.Messaging)this.Master.FindControl("errorMessaging"));
			messaging.Message = message;
			messaging.Title = title;
			messaging.ShowMessageDialog();
		}

		bool ValidatePageFields()
		{
			return (dpStartDate.IsValid && txtLicenseId.IsValid);
		}

        
        protected void gvLicenses_RowCommand1(object sender, GridViewCommandEventArgs e)
        {   
            int licenseId = Convert.ToInt32(e.CommandArgument);
            int AliasId = Convert.ToInt16(Session["CodAlia"]);
            int IdCorr = Convert.ToInt16(Session["CodCorr"]);
            String tipoLic = Convert.ToString(Session["TipoLic"]);
            
            if (e.CommandName == "AliasSelected")
            {
                if (licenseId != null)
                {
                    Response.Redirect("NewLicense.aspx?licenseId=" + licenseId + "&AliasId=" + AliasId + "&IdCorr=" + IdCorr + "&tipoLic=" + tipoLic);
                }

            }


        } 
        
	}
}